package cn.yanhu.kuwanapp.utils.ext

import androidx.lifecycle.MutableLiveData
import cn.woochen.comlib.BaseViewModel
import cn.woochen.comlib.config.RetrofitUtil
import cn.yanhu.kuwanapp.http.ApiService
import androidx.lifecycle.viewModelScope
import cn.yanhu.kuwanapp.http.status.*
import cn.yanhu.kuwanapp.http.status.paresResult
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

val BaseViewModel.rxApi: ApiService
    get() = RetrofitUtil.getInstance().retrofit?.create(ApiService::class.java)!!

/**
 * net request 不校验请求结果数据是否是成功
 * @param block 请求体方法
 * @param resultState 请求回调的ResultState数据
 * @param isShowDialog 是否显示加载框
 * @param loadingMessage 加载框提示内容
 */
fun <T> BaseViewModel.request(block: suspend () -> BaseBean<T>, resultState: MutableLiveData<ResultState<T>>, isShowDialog: Boolean = false, loadingMessage: Boolean = true): Job {
    return viewModelScope.launch {
        runCatching {
            if (isShowDialog) loadingChange.showDialog.postValue(loadingMessage)
            block()
        }.onSuccess {
            loadingChange.dismissDialog.postValue(false)
            logcom("request：bean:${it} code:${it.code} msg:${it.msg}")
            resultState.paresResult(it)
        }.onFailure {
            loadingChange.dismissDialog.postValue(false)
            resultState.paresException(it)
        }
    }
}

/**
 * 带有返回值的请求
 *
 * @param T
 * @param block
 * @param resultState
 * @param isShowDialog
 * @param loadingMessage
 * @return
 */
fun <T> BaseViewModel.request2(block: suspend () ->T, resultState: MutableLiveData<ResultState<T>>, isShowDialog: Boolean = false, loadingMessage: Boolean = true): Job {
    return viewModelScope.launch {
        runCatching {
            if (isShowDialog) loadingChange.showDialog.postValue(loadingMessage)
            block()
        }.onSuccess {
            loadingChange.dismissDialog.postValue(false)
            logcom("request_onSuccess：bean:${it}")
            resultState.paresResult(it)
        }.onFailure {
            logcom("request_onFailure：bean:${it}")
            loadingChange.dismissDialog.postValue(false)
            resultState.paresException(it)
        }
    }
}
